package dao;

import org.sqlite.SQLiteDataSource;

import javax.sql.DataSource;
import java.sql.*;

public class DBUtil {
    // 使用单例模式 来提供DataSource
    private static volatile DataSource dataSource = null;

    private static DataSource getDataSource() {
        if(dataSource == null) {
            synchronized (DBUtil.class) {
                if(dataSource == null) {
                    dataSource = new SQLiteDataSource();
                    ((SQLiteDataSource)dataSource).setUrl("jdbc:sqlite://D:/sq/sqlite-tools-win32-x86-3430200/fileSearcher.db");
                }
            }
        }
        return dataSource;
    }

    public static Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }

    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        if(resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(statement != null) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
